/**
 * @author cprobert
 */

var sonicAlert = {
	debug: false,
	networkMonitor: Object,
	arePrefsSet: false,
	init: function(){
		prefs.init();
		air.NativeApplication.nativeApplication.addEventListener(air.Event.NETWORK_CHANGE, sonicAlert.onNetworkChange);
		this.onNetworkChange(true); //check if available
	},
	onNetworkChange: function(e){
		sonicAlert.trace("Network Change: " + prefs.monitorURL);
		
		if ( prefs.monitorURL  == null || prefs.monitorURL == "" ) {
			sonicAlert.arePrefsSet = false;
			msg.toast( "Please set the monitor URL in the prefences" );
		}
		else {
			sonicAlert.arePrefsSet = true;
			try { //Check resource availability 
				sonicAlert.networkMonitor = new air.URLMonitor(new air.URLRequest( prefs.monitorURL ));
				sonicAlert.networkMonitor.addEventListener(air.StatusEvent.STATUS, sonicAlert.alertNetworkChange);
				sonicAlert.networkMonitor.start();
			} 
			catch (err) {
			 	msg.toast("Error communicating with "+ prefs.monitorURL);
			}
		}
	},
	alertNetworkChange: function(e){
		msg.toast( "Monitoring...<h1>" + sonicAlert.networkMonitor.available + "</h1>" );
		if (sonicAlert.networkMonitor.available) 
			listenUp.restart();
		else {
			listenUp.stop();
			air.NativeApplication.nativeApplication.icon.tooltip = "Network is offline";
			//I would like to change the systray icon if the network is offline
			// air.NativeApplication.nativeApplication.icon.bitmaps = [event.target.content.bitmapData];
			// air.NativeApplication.nativeApplication.icon.bitmaps = new Array(icon16x16.bitmapData, icon128x128.bitmapData);
			// air.NativeApplication.nativeApplication.icon.bitmaps = new Array(bitmapData);

			msg.toast("Monitor is unavailable");
		}
	},
	playSound: function(sound){
		sonicAlert.trace("Playing sound");
		var file = air.File.applicationDirectory.resolvePath(sound);
		var mp3 = new air.Sound(new air.URLRequest(file.url));
		mp3.play();
	},
	trace: function(value){
		if(sonicAlert.debug)
			air.trace(value);
	}
}

var prefs = {
	monitorURL: null,
	title: "",
	enableSound: true,
	enableToast: true,
	interval: 180,
	soundFile: 'sound/notify3.mp3',
	monitor: Object,
	init: function(){
		this.load();
	},
	load: function(){
		sonicAlert.trace( "loading prefs" );
		// this data access layer could be span out to a seperate class
		var monitorURL = air.EncryptedLocalStore.getItem('monitorURL');
		if(monitorURL)
			prefs.monitorURL = monitorURL.readUTFBytes( monitorURL.bytesAvailable );
		
		var title = air.EncryptedLocalStore.getItem('title');
		if(title)
			prefs.title = title.readUTFBytes( title.bytesAvailable );
			
		var interval = air.EncryptedLocalStore.getItem('interval')
		if (interval)
			prefs.interval = parseInt( interval.readUTFBytes( interval.bytesAvailable ) );
		
		var soundFile = air.EncryptedLocalStore.getItem('soundFile');
		if (soundFile)
			prefs.soundFile = soundFile.readUTFBytes( soundFile.bytesAvailable );
			
		var enableSound = air.EncryptedLocalStore.getItem('enableSound');
		if(enableSound)
			prefs.enableSound = (enableSound=='true'); //enableSound.readUTFBytes( enableSound.bytesAvailable );
		
		var enableToast = air.EncryptedLocalStore.getItem('enableToast');
		if(enableToast)
			prefs.enableToast = (enableToast=='true'); //enableToast.readUTFBytes( enableToast.bytesAvailable );
			
	},
	save: function(monitorURL, interval, soundFile, title, enableSound, enableToast){
		sonicAlert.trace( "saving prefs..." );
		var data = null;
		
		data = new air.ByteArray();
		data.writeUTFBytes( monitorURL );
		air.EncryptedLocalStore.setItem( 'monitorURL', data );
		
		data = new air.ByteArray();
		data.writeUTFBytes( title );
		air.EncryptedLocalStore.setItem( 'title', data );
		
		data = new air.ByteArray();
		data.writeUTFBytes( interval );
		air.EncryptedLocalStore.setItem( 'interval', data );
		
		data = new air.ByteArray();
		data.writeUTFBytes( soundFile );
		air.EncryptedLocalStore.setItem( 'soundFile', data );
		
		data = new air.ByteArray();
		data.writeUTFBytes( enableSound );
		air.EncryptedLocalStore.setItem( 'enableSound', data );
		
		data = new air.ByteArray();
		data.writeUTFBytes( enableToast );
		air.EncryptedLocalStore.setItem( 'enableToast', data );
		
		prefs.load();
		sonicAlert.networkMonitor.available = true;
		listenUp.restart();
	}
}

var listenUp = {
	count: Object,
	errorCount: 0,
	init: function(callback){
		listenUp.count = 0;
		
		if (air.EncryptedLocalStore.getItem('count')) 
			listenUp.count = parseInt(air.EncryptedLocalStore.getItem('count'))
		
		//listenUp.start(); // the network monitor now starts this
	},
	restart: function(){
		this.stop();
		this.start();
	},
	stop: function(){
		$(document).stopTime();
		sonicAlert.trace("Timer stoped!");
	},
	start: function(){
		var ms2s = prefs.interval * 1000 //convert miliseconds to seconds
		$(document).everyTime(ms2s, function(i){
			listenUp.getCount();
		});
		sonicAlert.trace("Timer started!");
	},
	setCount: function(count, message){
		if (count != listenUp.count) {
			
			sonicAlert.trace("Setting count = " + count);
			
			if (count > listenUp.count) { //&& count != 0
				sonicAlert.trace("Count has incremented");
				if (prefs.enableSound) {
					sonicAlert.playSound(prefs.soundFile);
				}
				if (prefs.enableToast) {
					msg.toast(message);
				}
			}
			else {
				sonicAlert.trace("Count has NOT incremented");
			}
			
			sonicAlert.trace("count = " + count + " listenUp.count = "+ listenUp.count);
			listenUp.count = count;
			
			var currentTime = new Date()
			var hours = currentTime.getHours()
			var minutes = currentTime.getMinutes()
			
			if (minutes < 10) 
				minutes = "0" + minutes
			
			var printTime = (hours + ":" + minutes + " ")
			if (hours > 11) 
				printTime += "PM";
			else 
				printTime += "AM";
			
			air.NativeApplication.nativeApplication.icon.tooltip = prefs.title + ": " + listenUp.count + " (" + printTime + ")";
			
			var data = null;
			data = new air.ByteArray();
			data.writeUTFBytes(listenUp.count);
			air.EncryptedLocalStore.setItem('count', data);
		}
	},
	getCount: function(){
		//sonicAlert.trace( prefs.monitorURL );
		if (sonicAlert.networkMonitor.available) {
			$.ajax({
				type: "GET",
				url: prefs.monitorURL,
				dataType: "json",
				success: function(json, textStatus){
					var c = 0;
					if (json.c) 
						c = json.c;
					
					var m = "";
					if (json.m) 
						m = json.m;
					
					var message = prefs.title + ": <h1>" + c + "</h1> "+ m;
					sonicAlert.trace( "From server = "+ message );
					listenUp.setCount(c, message);
					
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					listenUp.errorCount++;
					
					var errMsg = "Error:", errorThrown;
					sonicAlert.trace(errMsg);
					msg.toast(errMsg);
					
					air.NativeApplication.nativeApplication.icon.tooltip = "Error:", errorThrown;
					sonicAlert.playSound('sound/error.mp3');
					if (listenUp.errorCount > 10){
						listenUp.stop();
						msg.toast("<h1>Monitor disabled</h1>");
					}
				}
			});
		}
		else {
			msg.toast("<h1>Monitor is offline</h1>");
		}
	}
}

var msg = {
	text: "",
	toast: function(value){
		msg.text = value;
		
		try {
			var options = new air.NativeWindowInitOptions();
			options.systemChrome = air.NativeWindowSystemChrome.STANDARD;
			options.type = air.NativeWindowType.UTILITY
			options.maximizable = false;
			options.minimizable = false;
			options.transparent = false;
			options.resizable = false;
			
			var windowBounds = new air.Rectangle((screen.width - 155), (screen.height - 180), 150, 150);
			var toastHTMLLoader = air.HTMLLoader.createRootWindow(true, options, true, windowBounds);
			var toastPage = air.File.applicationDirectory.resolvePath("toast.html");
			toastHTMLLoader.load(new air.URLRequest(toastPage.url));
			toastHTMLLoader.window.opener = window;
		} 
		catch (err) {
			alert(msg.text);
		}
		sonicAlert.trace("Toast: "+ msg.text);
	}
};
